package simulation;

public class GameOfLife289 {
    int[][] direct = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};

    private boolean judge(int i, int j, int[][] board) {
        int live = 0;
//        int dead = 0;
        for (int k = 0; k < direct.length; k++) {
            int x = i + direct[k][0];
            int y = j + direct[k][1];
            if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) {
                continue;
            }
//            //死的，以及死的应该复活的
//            if (board[x][y] == 0 || board[x][y] == 2) {
//                dead++;
//            }
            //活的，以及活的要死的
            if (board[x][y] == 1 || board[x][y] == -1) {
                live++;
            }
        }
        if (board[i][j] == 1 && live < 2) {
            return false;
        }
        if (board[i][j] == 1 && (live == 2 || live == 3)) {
            return true;
        }
        if (board[i][j] == 1&&live > 3) {
            return false;
        }
        if(board[i][j] == 0&&live==3){
            return true;
        }
        return false;
    }

    public void gameOfLife(int[][] board) {
        if (board == null || board.length == 0 || board[0].length == 0) {
            return;
        }

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                boolean result = judge(i, j, board);
                //死亡复活，置为2
                if (result && board[i][j] == 0) {
                    board[i][j] = 2;
                }
                //活着死亡，置为-1
                if (!result && board[i][j] == 1) {
                    board[i][j] = -1;
                }
            }
        }

        //原地恢复
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == -1) {
                    board[i][j] = 0;
                }
                if (board[i][j] == 2) {
                    board[i][j] = 1;
                }
            }
        }
    }
}
